"use client"

import { useState, useEffect, useRef } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Platform, Animated, Dimensions, Image } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { LinearGradient } from "expo-linear-gradient"
import { ArrowLeft, CheckCircle2, XCircle } from "lucide-react-native"
import { useRouter } from "expo-router"
import { theme } from "../../constants/theme"
import { ProgressBar } from "../../components/practices/ProgressBar"

// 获取屏幕尺寸
const { width } = Dimensions.get("window")
const isTablet = width > 768

// 模拟的单词数据
const WORD_DATA = [
    { id: "1", word: "apple", phonetic: "/ˈæp.əl/", meaning: "苹果" },
    { id: "2", word: "banana", phonetic: "/bəˈnɑː.nə/", meaning: "香蕉" },
    { id: "3", word: "orange", phonetic: "/ˈɒr.ɪndʒ/", meaning: "橙子" },
    { id: "4", word: "grape", phonetic: "/ɡreɪp/", meaning: "葡萄" },
    { id: "5", word: "watermelon", phonetic: "/ˈwɔː.tə.mel.ən/", meaning: "西瓜" },
    { id: "6", word: "strawberry", phonetic: "/ˈstrɔː.bər.i/", meaning: "草莓" },
    { id: "7", word: "pear", phonetic: "/peər/", meaning: "梨" },
    { id: "8", word: "peach", phonetic: "/piːtʃ/", meaning: "桃子" },
    { id: "9", word: "pineapple", phonetic: "/ˈpaɪn.æp.əl/", meaning: "菠萝" },
    { id: "10", word: "cherry", phonetic: "/ˈtʃer.i/", meaning: "樱桃" },
    { id: "11", word: "lemon", phonetic: "/ˈlem.ən/", meaning: "柠檬" },
    { id: "12", word: "mango", phonetic: "/ˈmæŋ.ɡəʊ/", meaning: "芒果" },
    { id: "13", word: "kiwi", phonetic: "/ˈkiː.wiː/", meaning: "猕猴桃" },
    { id: "14", word: "coconut", phonetic: "/ˈkəʊ.kə.nʌt/", meaning: "椰子" },
    { id: "15", word: "avocado", phonetic: "/æv.əˈkɑː.dəʊ/", meaning: "牛油果" },
    { id: "16", word: "blueberry", phonetic: "/ˈbluː.bər.i/", meaning: "蓝莓" },
    { id: "17", word: "raspberry", phonetic: "/ˈrɑːz.bər.i/", meaning: "覆盆子" },
    { id: "18", word: "blackberry", phonetic: "/ˈblæk.bər.i/", meaning: "黑莓" },
    { id: "19", word: "plum", phonetic: "/plʌm/", meaning: "李子" },
    { id: "20", word: "fig", phonetic: "/fɪɡ/", meaning: "无花果" },
]

// 每页显示的单词数量
const WORDS_PER_PAGE = 5

export default function WordMatchScreen() {
    const router = useRouter()
    const [currentPage, setCurrentPage] = useState(0)
    const [totalPages, setTotalPages] = useState(Math.ceil(WORD_DATA.length / WORDS_PER_PAGE))
    const [currentWords, setCurrentWords] = useState<typeof WORD_DATA>([])
    const [shuffledMeanings, setShuffledMeanings] = useState<Array<{ id: string; meaning: string }>>([])
    const [selectedWord, setSelectedWord] = useState<string | null>(null)
    const [selectedMeaning, setSelectedMeaning] = useState<string | null>(null)
    const [matchedPairs, setMatchedPairs] = useState<Set<string>>(new Set())
    const [correctCount, setCorrectCount] = useState(0)
    const [errorCount, setErrorCount] = useState(0)
    const [showFeedback, setShowFeedback] = useState(false)
    const [isCorrect, setIsCorrect] = useState(false)
    const [completed, setCompleted] = useState(false)
    const [erroredWords, setErroredWords] = useState<Set<string>>(new Set())

    // 动画值
    const feedbackAnim = useRef(new Animated.Value(0)).current
    const wordScaleAnim = useRef(new Animated.Value(1)).current
    const meaningScaleAnim = useRef(new Animated.Value(1)).current

    // 初始化当前页的单词
    useEffect(() => {
        loadWordsForCurrentPage()
    }, [currentPage])

    // 加载当前页的单词
    const loadWordsForCurrentPage = () => {
        const startIndex = currentPage * WORDS_PER_PAGE
        const endIndex = Math.min(startIndex + WORDS_PER_PAGE, WORD_DATA.length)
        const pageWords = WORD_DATA.slice(startIndex, endIndex)

        setCurrentWords(pageWords)

        // 打乱中文意思的顺序
        const meanings = pageWords.map((word) => ({ id: word.id, meaning: word.meaning }))
        setShuffledMeanings(shuffleArray([...meanings]))

        // 重置选择状态
        setSelectedWord(null)
        setSelectedMeaning(null)
        setShowFeedback(false)
    }

    // 打乱数组顺序
    const shuffleArray = <T,>(array: T[]): T[] => {
        const newArray = [...array]
        for (let i = newArray.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1))
                ;[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
        }
        return newArray
    }

    // 处理单词点击
    const handleWordSelect = (wordId: string) => {
        // 如果该单词已经匹配，则不做任何操作
        if (matchedPairs.has(wordId)) return

        // 如果正在显示反馈，则不做任何操作
        if (showFeedback) return

        // 设置选中的单词
        setSelectedWord(wordId)

        // 如果已经选中了中文意思，则检查匹配
        if (selectedMeaning !== null) {
            checkMatch(wordId, selectedMeaning)
        }

        // 单词选中动画
        Animated.sequence([
            Animated.timing(wordScaleAnim, {
                toValue: 0.95,
                duration: 100,
                useNativeDriver: true,
            }),
            Animated.timing(wordScaleAnim, {
                toValue: 1,
                duration: 100,
                useNativeDriver: true,
            }),
        ]).start()
    }

    // 处理中文意思点击
    const handleMeaningSelect = (meaningId: string) => {
        // 如果该意思对应的单词已经匹配，则不做任何操作
        if (matchedPairs.has(meaningId)) return

        // 如果正在显示反馈，则不做任何操作
        if (showFeedback) return

        // 设置选中的中文意思
        setSelectedMeaning(meaningId)

        // 如果已经选中了单词，则检查匹配
        if (selectedWord !== null) {
            checkMatch(selectedWord, meaningId)
        }

        // 中文意思选中动画
        Animated.sequence([
            Animated.timing(meaningScaleAnim, {
                toValue: 0.95,
                duration: 100,
                useNativeDriver: true,
            }),
            Animated.timing(meaningScaleAnim, {
                toValue: 1,
                duration: 100,
                useNativeDriver: true,
            }),
        ]).start()
    }

    // 检查匹配
    const checkMatch = (wordId: string, meaningId: string) => {
        // 判断是否匹配
        const isMatch = wordId === meaningId

        setIsCorrect(isMatch)
        setShowFeedback(true)

        // 显示反馈动画
        Animated.timing(feedbackAnim, {
            toValue: 1,
            duration: 300,
            useNativeDriver: true,
        }).start()

        // 延迟处理匹配结果
        setTimeout(() => {
            if (isMatch) {
                // 匹配成功
                setMatchedPairs((prev) => new Set([...prev, wordId]))
                setCorrectCount((prev) => prev + 1)

                // 检查当前页是否完成
                const newMatchedPairs = new Set([...matchedPairs, wordId])
                const isPageCompleted = currentWords.every((word) => newMatchedPairs.has(word.id))

                if (isPageCompleted) {
                    // 检查是否所有页面都完成
                    if (currentPage === totalPages - 1) {
                        // 所有页面都完成
                        setCompleted(true)
                    } else {
                        // 进入下一页
                        setTimeout(() => {
                            setCurrentPage((prev) => prev + 1)
                        }, 500)
                    }
                }
            } else {
                // 匹配失败
                if (!erroredWords.has(wordId)) {
                    setErrorCount((prev) => prev + 1)
                    setErroredWords((prev) => new Set([...prev, wordId]))
                }
            }

            // 重置选择状态
            setSelectedWord(null)
            setSelectedMeaning(null)
            setShowFeedback(false)
            feedbackAnim.setValue(0)
        }, 1000)
    }

    // 返回上一页
    const handleBack = () => {
        router.back()
    }

    // 重新开始
    const handleRestart = () => {
        setCurrentPage(0)
        setMatchedPairs(new Set())
        setCorrectCount(0)
        setErrorCount(0)
        setErroredWords(new Set())
        setCompleted(false)
    }

    // 完成练习
    const handleComplete = () => {
        router.back()
    }

    // 获取单词卡片样式
    const getWordCardStyle = (wordId: string) => {
        if (matchedPairs.has(wordId)) {
            return [styles.wordCard, styles.matchedCard]
        }
        if (selectedWord === wordId) {
            return [styles.wordCard, styles.selectedWordCard]
        }
        return [styles.wordCard]
    }

    // 获取中文意思卡片样式
    const getMeaningCardStyle = (meaningId: string) => {
        if (matchedPairs.has(meaningId)) {
            return [styles.meaningCard, styles.matchedCard]
        }
        if (selectedMeaning === meaningId) {
            return [styles.meaningCard, styles.selectedMeaningCard]
        }
        return [styles.meaningCard]
    }

    // 渲染完成页面
    if (completed) {
        return (
            <SafeAreaView style={styles.container} edges={["top"]}>
                <LinearGradient
                    colors={theme.colors.neutral.backgroundGradient}
                    start={{ x: 0, y: 0 }}
                    end={{ x: 0, y: 1 }}
                    style={styles.gradientBackground}
                >
                    <View style={styles.header}>
                        <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                            <ArrowLeft size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>
                        <Text style={styles.headerTitle}>单词对对碰</Text>
                        <View style={{ width: 40 }} />
                    </View>

                    <View style={styles.completedContainer}>
                        <Image
                            source={{ uri: "https://cdn-icons-png.flaticon.com/512/4341/4341047.png" }}
                            style={styles.completedImage}
                        />
                        <Text style={styles.completedTitle}>练习完成！</Text>
                        <Text style={styles.completedScore}>
                            正确: {correctCount} / 错误: {errorCount}
                        </Text>
                        <Text style={styles.completedMessage}>
                            {errorCount === 0
                                ? "太棒了！你没有犯任何错误！"
                                : errorCount <= 5
                                    ? "做得不错！再接再厉！"
                                    : "继续努力，你会做得更好！"}
                        </Text>

                        <View style={styles.completedButtons}>
                            <TouchableOpacity style={styles.restartButton} onPress={handleRestart}>
                                <Text style={styles.restartButtonText}>再来一次</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={styles.completeButton} onPress={handleComplete}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.completeButtonGradient}
                                >
                                    <Text style={styles.completeButtonText}>完成练习</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>
                    </View>
                </LinearGradient>
            </SafeAreaView>
        )
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            <LinearGradient
                colors={theme.colors.neutral.backgroundGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.gradientBackground}
            >
                {/* 头部 */}
                <View style={styles.header}>
                    <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                        <ArrowLeft size={24} color={theme.colors.neutral.black} />
                    </TouchableOpacity>
                    <Text style={styles.headerTitle}>单词对对碰</Text>
                    <View style={{ width: 40 }} />
                </View>

                {/* 进度条 */}
                <ProgressBar current={correctCount} total={WORD_DATA.length} showText={true} textPosition="top" />

                {/* 错题数 */}
                <View style={styles.errorContainer}>
                    <Text style={styles.errorText}>错题数: {errorCount}</Text>
                </View>

                {/* 主要内容 */}
                <View style={styles.content}>
                    {/* 反馈提示 */}
                    {showFeedback && (
                        <Animated.View
                            style={[
                                styles.feedbackContainer,
                                isCorrect ? styles.correctFeedback : styles.wrongFeedback,
                                {
                                    opacity: feedbackAnim,
                                    transform: [
                                        {
                                            translateY: feedbackAnim.interpolate({
                                                inputRange: [0, 1],
                                                outputRange: [20, 0],
                                            }),
                                        },
                                    ],
                                },
                            ]}
                        >
                            {isCorrect ? (
                                <View style={styles.feedbackContent}>
                                    <View style={styles.feedbackIconContainer}>
                                        <CheckCircle2 size={20} color={theme.colors.neutral.white} />
                                    </View>
                                    <Text style={styles.correctFeedbackText}>匹配正确！</Text>
                                </View>
                            ) : (
                                <View style={[styles.feedbackContent]}>
                                    <View style={[styles.feedbackIconContainer, styles.wrongFeedbackIcon]}>
                                        <XCircle size={20} color={theme.colors.neutral.white} />
                                    </View>
                                    <Text style={styles.wrongFeedbackText}>匹配错误！</Text>
                                </View>
                            )}
                        </Animated.View>
                    )}

                    {/* 单词卡片 */}
                    <View style={styles.cardsContainer}>
                        <View style={styles.wordCardsContainer}>
                            <Text style={styles.columnTitle}>英文单词</Text>
                            {currentWords.map((word) => (
                                <Animated.View
                                    key={`word-${word.id}`}
                                    style={[
                                        { transform: [{ scale: selectedWord === word.id ? wordScaleAnim : 1 }] },
                                        matchedPairs.has(word.id) && styles.matchedCardContainer,
                                    ]}
                                >
                                    <TouchableOpacity
                                        style={getWordCardStyle(word.id)}
                                        onPress={() => handleWordSelect(word.id)}
                                        disabled={matchedPairs.has(word.id)}
                                        activeOpacity={0.8}
                                    >
                                        <Text style={styles.wordText}>{word.word}</Text>
                                        <Text style={styles.phoneticText}>{word.phonetic}</Text>
                                    </TouchableOpacity>
                                </Animated.View>
                            ))}
                        </View>

                        <View style={styles.meaningCardsContainer}>
                            <Text style={styles.columnTitle}>中文释义</Text>
                            {shuffledMeanings.map((item) => (
                                <Animated.View
                                    key={`meaning-${item.id}`}
                                    style={[
                                        { transform: [{ scale: selectedMeaning === item.id ? meaningScaleAnim : 1 }] },
                                        matchedPairs.has(item.id) && styles.matchedCardContainer,
                                    ]}
                                >
                                    <TouchableOpacity
                                        style={getMeaningCardStyle(item.id)}
                                        onPress={() => handleMeaningSelect(item.id)}
                                        disabled={matchedPairs.has(item.id)}
                                        activeOpacity={0.8}
                                    >
                                        <Text style={styles.meaningText}>{item.meaning}</Text>
                                    </TouchableOpacity>
                                </Animated.View>
                            ))}
                        </View>
                    </View>

                    {/* 页面指示器 */}
                    <View style={styles.paginationContainer}>
                        <Text style={styles.paginationText}>
                            第 {currentPage + 1} 页 / 共 {totalPages} 页
                        </Text>
                    </View>
                </View>
            </LinearGradient>
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    gradientBackground: {
        flex: 1,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
    },
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    errorContainer: {
        alignItems: "flex-end",
        paddingHorizontal: theme.spacing.lg,
        marginBottom: theme.spacing.md,
    },
    errorText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.secondary.red.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    content: {
        flex: 1,
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
    },
    feedbackContainer: {
        position: "absolute",
        top: 0,
        left: 0,
        right: 0,
        zIndex: 10,
        padding: theme.spacing.md,
        borderRadius: theme.borderRadius.large,
        marginBottom: theme.spacing.md,
        alignItems: "center",
    },
    feedbackContent: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center",
        gap: theme.spacing.sm,
    },
    correctFeedback: {
        backgroundColor: "rgba(52, 199, 89, 0.1)",
    },
    wrongFeedback: {
        backgroundColor: "rgba(255, 59, 48, 0.1)",
    },
    correctFeedbackText: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.green.default,
    },
    wrongFeedbackText: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.red.default,
    },
    cardsContainer: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "space-between",
        marginTop: theme.spacing.xl,
    },
    columnTitle: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.md,
        textAlign: "center",
    },
    wordCardsContainer: {
        flex: 1,
        marginRight: theme.spacing.md,
    },
    meaningCardsContainer: {
        flex: 1,
        marginLeft: theme.spacing.md,
    },
    wordCard: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        alignItems: "center",
        justifyContent: "center",
        minHeight: 80,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.3,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    meaningCard: {
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.lg,
        marginBottom: theme.spacing.md,
        alignItems: "center",
        justifyContent: "center",
        minHeight: 80,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 2 },
                shadowOpacity: 0.3,
                shadowRadius: 4,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    selectedWordCard: {
        borderWidth: 2,
        borderColor: theme.colors.primary.default,
        backgroundColor: "rgba(91, 142, 244, 0.05)",
    },
    selectedMeaningCard: {
        borderWidth: 2,
        borderColor: theme.colors.secondary.orange.default,
        backgroundColor: "rgba(255, 149, 0, 0.05)",
    },
    matchedCard: {
        opacity: 0.3,
        backgroundColor: "rgba(52, 199, 89, 0.1)",
    },
    matchedCardContainer: {
        opacity: 0.3,
    },
    wordText: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.xs,
    },
    phoneticText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
    },
    meaningText: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    paginationContainer: {
        alignItems: "center",
        marginTop: theme.spacing.lg,
        marginBottom: theme.spacing.lg,
    },
    paginationText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
    },
    // 完成页面样式
    completedContainer: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
        paddingHorizontal: theme.spacing.xl,
    },
    completedImage: {
        width: 150,
        height: 150,
        marginBottom: theme.spacing.xl,
    },
    completedTitle: {
        fontSize: isTablet ? 36 : 28,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.lg,
    },
    completedScore: {
        fontSize: isTablet ? theme.fontSize.xl : theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.md,
    },
    completedMessage: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        textAlign: "center",
        marginBottom: theme.spacing.xxxl,
    },
    completedButtons: {
        flexDirection: "row",
        gap: theme.spacing.lg,
        width: "100%",
        maxWidth: 400,
    },
    restartButton: {
        flex: 1,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: theme.borderRadius.large,
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    restartButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    completeButton: {
        flex: 1,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 3 },
                shadowOpacity: 0.3,
                shadowRadius: 5,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    completeButtonGradient: {
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
        justifyContent: "center",
    },
    completeButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
    feedbackIconContainer: {
        width: 28,
        height: 28,
        borderRadius: 14,
        backgroundColor: theme.colors.secondary.green.default,
        alignItems: "center",
        justifyContent: "center",
        marginRight: theme.spacing.sm,
    },
    wrongFeedbackIcon: {
        backgroundColor: theme.colors.secondary.red.default,
    },
})

